package core;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import events.LibraryChangeEvent;
import events.LibraryListener;

public abstract class AbstractMusicLibrary implements MusicLibrary {

	protected final List<Song> musicCollection = new ArrayList<Song>();
	protected final LinkedList<LibraryListener> listeners = new LinkedList<LibraryListener>();
	protected long totalTime = 0, totalSize = 0;
	private final LibraryChangeEvent event = new LibraryChangeEvent(this);

	@Override
	public Collection<Song> getAllMusic() {
		return musicCollection;
	}

	@Override
	public void addSong(Song song) {
		musicCollection.add(song);
		totalTime += song.getTotalTime();
		totalSize += song.getFileSize();
		for (LibraryListener listener : listeners) {
			listener.libraryChanged(event);
		}
	}

	@Override
	public long getTotalSize() {
		return totalSize;
	}

	@Override
	public long getTotalTime() {
		return totalTime;
	}

	@Override
	public void removeSong(Song song) {
		if (musicCollection.remove(song)) {
			totalTime -= song.getTotalTime();
			totalSize -= song.getFileSize();
			for (LibraryListener listener : listeners) {
				listener.libraryChanged(event);
			}
		}
	}

	@Override
	public void addLibraryListener(LibraryListener listener) {
		if (listeners.contains(listener) == false)
			listeners.add(listener);
	}

	@Override
	public void removeLibraryListener(LibraryListener listener) {
		listeners.remove(listener);
	}

	public int getNumSongs() {
		return musicCollection.size();
	}

	public Song getSongAt(int index) {
		if (index < 0 || index >= musicCollection.size())
			return null;
		return musicCollection.get(index);
	}

	public boolean removeSongAt(int index) {
		if (index < 0 || index >= musicCollection.size())
			return false;
		musicCollection.remove(index);
		for (LibraryListener listener : listeners) {
			listener.libraryChanged(event);
		}
		return true;
	}

}
